package 多线程;

/**
 * @Author: 朱胜伟
 * @CreateTime: 2021-02-01 15:12
 * @Description:
 */
public class CASTest {
    public static void main(String[] args) {
        CASCounter casCounter = new CASCounter();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    casCounter.incrementAndGet();
                }
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println(casCounter.getValue());

    }
}
class CASCounter{
    volatile private long value = 0;

    public long getValue() {
        return value;
    }
    //定义 comare and swap方法
    private boolean compareAndSwap(long exepectedValue,long newValue){
        synchronized (this){
            if(value == exepectedValue){
                value = newValue;
                return true;
            }else {
                System.err.println("冲突了");
                return false;
            }
        }
    }
    public long incrementAndGet(){

        long oldvalue;
        long newValue;
        do {
            oldvalue = value;
            newValue = oldvalue+1;
        }while (!compareAndSwap(oldvalue,newValue));
        return value;
    }
}
